//
// Created by Scave on 2023/11/9.
//

#include "RenderContext.h"
#include "bgfx/BgfxUtil.h"

NS_RIDER_BEGIN

    RenderContext::RenderContext(const RenderConfig& config) {
        this->render_config_ = config;
    }

    RenderContext::~RenderContext() {
    }

    BufferHandle* RenderContext::CreateOrUpdateBuffer(Name& name,
                                                      SMART_PTR<ShaderProgram>& shader_program,
                                                      std::vector<Vertex>& vertex_list,
                                                      std::vector<UInt16>& index_list) {
        if (name_buffer_handle_map_.find(name) != name_buffer_handle_map_.end()) {
            return name_buffer_handle_map_[name];
        } else {
            RectifyVertices(vertex_list);
            Vertex* vertices = vertex_list.data();
            UInt16* indices = index_list.data();
            auto vertex_ref = bgfx::makeRef(vertices, sizeof(Vertex) * vertex_list.size());
            auto index_ref = bgfx::makeRef(indices, sizeof(UInt16) * index_list.size());
            bgfx::VertexBufferHandle vertex_buffer =
                    bgfx::createVertexBuffer(vertex_ref, shader_program->vertex_layout_);
            bgfx::IndexBufferHandle index_buffer = bgfx::createIndexBuffer(index_ref);
            BufferHandle* handle = new BufferHandle{vertices, indices};
            handle->vertex_buffer_static = vertex_buffer;
            handle->index_buffer_static = index_buffer;
            PutBufferHandle(name, handle);
            return handle;
        }
    }

    BufferHandle* RenderContext::GetBufferHandle(const Name& name) {
        if (name_buffer_handle_map_.find(name) == name_buffer_handle_map_.end()) {
            return nullptr;
        }
        return name_buffer_handle_map_[name];
    }

    void RenderContext::PutBufferHandle(const Name& name, BufferHandle* handle) {
        name_buffer_handle_map_[name] = handle;
    }

    void RenderContext::RectifyVertices(std::vector<Vertex>& vertex_list) {
#if defined(ANDROID) || defined(HARMONY)
        for (auto& vertex: vertex_list) {
            vertex.uv.v = -vertex.uv.v;
        }
#endif
    }

NS_RIDER_END
